package com.zline.foodraise.ui.fragment;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.MsgNoticeRedPointBean;
import com.zline.foodraise.entity.OrderRedPointBean;
import com.zline.foodraise.entity.RedPointBean;
import com.zline.foodraise.entity.ShopApplyBean;
import com.zline.foodraise.entity.UserBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.FragmentListener;
import com.zline.foodraise.ui.activity.EventNoticeActivity_;
import com.zline.foodraise.ui.activity.FeedbackActivity_;
import com.zline.foodraise.ui.activity.MsgCentreActivity_;
import com.zline.foodraise.ui.activity.OpenShopActivity_;
import com.zline.foodraise.ui.activity.PersonalHomePageActivity_;
import com.zline.foodraise.ui.activity.ProductOrderActivity_;
import com.zline.foodraise.ui.activity.ProjectOrderActivity_;
import com.zline.foodraise.ui.activity.ProjectOrderManagerActivity_;
import com.zline.foodraise.ui.activity.RaiseShopActivity_;
import com.zline.foodraise.ui.activity.ReleaseDynamicActivity_;
import com.zline.foodraise.ui.activity.WalletActivity_;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.CircleImageView;
import com.zline.foodraise.view.dialog.LoadingProgressDialog;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/12/24.
 * 我
 */
@EFragment(R.layout.me_fragment)
public class MeFragment extends Fragment {
    private static final String LOG_TAG = MeFragment.class.getSimpleName();
    //用户头像
    @ViewById(R.id.me_person_icon_civ)
    CircleImageView me_person_icon_civ;
    @ViewById(R.id.me_person_icon_vip)
    ImageView me_person_icon_vip;
    //用户粉丝数
    @ViewById(R.id.me_person_fans_tv)
    TextView fans_num_tv;
    @StringRes(R.string.fans)
    String fans;
    //用户粉丝数量
    int fansCount;
    //用户关注数
    @ViewById(R.id.me_person_attion_tv)
    TextView attention_num_tv;
    @StringRes(R.string.attention)
    String attentions;
    //用户关注数
    int attentionCount;
    //昵称
    @ViewById(R.id.me_person_nickname_tv)
    TextView nickname_tv;
    //签名
    @ViewById(R.id.me_person_signature_tv)
    TextView signature_tv;
    @ViewById(R.id.me_fragment_open_shop_rl)
    RelativeLayout open_shop_rl;
    @ViewById(R.id.me_fragment_merchant_rl)
    RelativeLayout merchant_rl;
    //消息中心小红点
    @ViewById(R.id.me_fragment_msg_red_point)
    View msg_red_point_view;
    //活动公告小红点
    @ViewById(R.id.me_fragment_event_notice_red_point)
    View notice_red_point_view;
    //未付款小红点
    @ViewById(R.id.me_fragment_unpay_red_point)
    View unpay_red_point_view;
    //未确定小红点
    @ViewById(R.id.me_fragment_unconfirm_red_point)
    View unconfirm_red_point_view;
    //商家未处理小红点
    @ViewById(R.id.me_fragment_waiting_order_red_point)
    View unHandler_red_point_view;
    Context cxt;
    long userId;
    @Pref
    AppPref_ appPref;
    @Bean
    NetworkUtil networkUtil;
    LoadingProgressDialog loadDialog;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    @Bean
    ImageUtil imageUtil;
    //店铺申请状态 状态 0:审核中 1:通过 2:驳回 3:未提交申请
    int shopStatus;
    //开店驳回原因
    String rejectReason;
    RedPointBean redPointBean;
    FragmentListener fragmentListener;
    //最新的活动公告Id
    long noticeId;
    //最新的消息Id
    long msgId;
    //最新一条未支付筹订单Id
    long lastUnPayCfOrderId;
    // 最新一条未确认筹订单Id
    long lastUnConfirmedCfOrderId;
    //最新一条商家未处理筹订单Id
    long lastUnHandleCfOrderId;
    MsgNoticeRedPointBean msgNoticeRedPointBean;
    OrderRedPointBean orderRedPointBean;

    @AfterInject
    void doSomeAfterInject() {
        cxt = getActivity();
        userId = appPref.userId().get();
    }

    @AfterViews
    void doSomeAfterView() {
        requestData();
    }

    //请求网络数据
    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestUserInfo();
        } else {
            TUtil.showShort(cxt, R.string.no_network);
        }
    }


    //请求用户基本信息
    void requestUserInfo() {
        httpOperator.requestUserInfo(httpUtil, userId, requestUserInfoHandler);
    }

    //获取用户基本信息回调
    AsyncHttpResponseHandler requestUserInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestUserInfoHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        UserBean userBean = httpDataParsing.getUserBean(response);
                        setUserInfo(userBean);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };


    //设置用户基本信息
    void setUserInfo(UserBean userBean) {
        if (userBean != null) {
            ImageLoader imageLoader = ImageLoader.getInstance();
            DisplayImageOptions person_icon_options = imageUtil.
                    getDisplayImageOptions(R.mipmap.default_person_icon,
                            R.mipmap.default_person_icon, R.mipmap.default_person_icon);
            fansCount = userBean.getUserFansCount();
            fans_num_tv.setText(fansCount + fans);
            attentionCount = userBean.getUserAttentionCount();
            attention_num_tv.setText(attentionCount + attentions);
            String person_ico_url = userBean.getAvatarPicUrl();
            int authenticateType = userBean.getIdentificateType();
            imageLoader.displayImage(person_ico_url, me_person_icon_civ, person_icon_options);
            if (authenticateType == 1) {//大V
                me_person_icon_vip.setVisibility(View.VISIBLE);
            }

            String nickname = userBean.getNickName();
            nickname_tv.setText(nickname);
            String signature = userBean.getSignature();
            signature_tv.setText(signature);
            int isOpenShop = userBean.getIsOpenShop();
            if (isOpenShop == 1) {
                open_shop_rl.setVisibility(View.GONE);
                merchant_rl.setVisibility(View.VISIBLE);
            } else {
                open_shop_rl.setVisibility(View.VISIBLE);
                merchant_rl.setVisibility(View.GONE);
                requestShopApplyInfo();
            }
        }
    }

    //获取店铺申请状态信息
    void requestShopApplyInfo() {
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requstShopApplyInfo(httpUtil, userId, requestShopApplyInfoHandler);
        } else {
            TUtil.showShort(cxt, R.string.no_network);
        }
    }

    //获取用户店铺状态申请回调
    AsyncHttpResponseHandler requestShopApplyInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestShopApplyInfoHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        ShopApplyBean shopApplyBean = httpDataParsing.getShopApplyBean(response);
                        getShopInfo(shopApplyBean);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            LUtil.i(LOG_TAG, "____failure__________" + responseString.toString());
        }
    };

    //获得申请店铺详情
    void getShopInfo(ShopApplyBean shopApplyBean) {
        if (shopApplyBean != null) {
            if (StringUtils.isBlank(shopApplyBean.getAddress())
                    && StringUtils.isBlank(shopApplyBean.getContact())) {
                shopStatus = 3;
            } else {
                shopStatus = shopApplyBean.getStatus();
                rejectReason = shopApplyBean.getRejectReason();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        showMeRedPointBean();
    }

    //显示加载对话框
    void showLoadingDialog() {
        loadDialog = LoadingProgressDialog.init(cxt);
        loadDialog.show();
    }

    //加载框消失
    void dissLoadingDialog() {
        if (loadDialog != null) {
            loadDialog.dismiss();
        }
    }


    //设置监听器
    public void setFragmentListener(FragmentListener listener) {
        this.fragmentListener = listener;
    }


    //设置fragment 中红点信息
    public void setRedPointBean(RedPointBean bean) {
        this.redPointBean = bean;
    }

    //小红点信息的展示、隐藏
    void showMeRedPointBean() {
        if (redPointBean != null) {
            msgNoticeRedPointBean = redPointBean.getMsgNoticeRedPointBean();
            orderRedPointBean = redPointBean.getOrderRedPointBean();
            if (msgNoticeRedPointBean != null) {
                noticeId = msgNoticeRedPointBean.getLastNoticeId();
                msgId = msgNoticeRedPointBean.getLastSysPushId();
            }
            if (orderRedPointBean != null) {
                lastUnPayCfOrderId = orderRedPointBean.getLastUnPayCfOrderId();
                lastUnConfirmedCfOrderId = orderRedPointBean.getLastUnConfirmedCfOrderId();
                lastUnHandleCfOrderId = orderRedPointBean.getLastUnHandleCfOrderId();
            }
            if (appPref.lastMsgId().get() < msgId) {
                msg_red_point_view.setVisibility(View.VISIBLE);
            } else {
                msg_red_point_view.setVisibility(View.GONE);
            }
            if (appPref.lastNoticeId().get() < noticeId) {
                notice_red_point_view.setVisibility(View.VISIBLE);
            } else {
                notice_red_point_view.setVisibility(View.GONE);
            }

            if (0 < lastUnHandleCfOrderId) {
                unHandler_red_point_view.setVisibility(View.VISIBLE);
            } else {
                unHandler_red_point_view.setVisibility(View.GONE);
            }
            if (0 < lastUnPayCfOrderId) {
                unpay_red_point_view.setVisibility(View.VISIBLE);
            } else {
                unpay_red_point_view.setVisibility(View.GONE);
            }
            if (0 < lastUnConfirmedCfOrderId) {
                unconfirm_red_point_view.setVisibility(View.VISIBLE);
            } else {
                unconfirm_red_point_view.setVisibility(View.GONE);
            }

            if (0 < lastUnPayCfOrderId
                    || 0 < lastUnConfirmedCfOrderId
                    || 0 < lastUnHandleCfOrderId
                    || appPref.lastMsgId().get() < msgId
                    || appPref.lastNoticeId().get() < noticeId) {
                fragmentListener.showMeRedPoint(true);
            } else {
                fragmentListener.showMeRedPoint(false);
            }
        }
    }


    @Click({R.id.me_fragment_all_cc_tv, R.id.me_top_person_info_rl
            , R.id.open_shop_iv, R.id.me_fragment_my_wallet_tv, R.id.me_fragment_msg_tv
            , R.id.me_fragment_event_notice_tv, R.id.me_fragment_release_dynamic_tv
            , R.id.me_fragment_waiting_order_tv, R.id.me_fragment_all_orders_tv
            , R.id.me_fragment_cc_order_tv, R.id.me_fragment_product_order_tv
            , R.id.me_fragment_unpay_tv, R.id.me_fragment_unconfirm_tv
            , R.id.me_fragment_feedback_tv

    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.me_fragment_all_cc_tv:
                RaiseShopActivity_.intent(cxt).start();
                break;
            case R.id.me_top_person_info_rl:
                PersonalHomePageActivity_.intent(cxt).userId(userId).start();
                break;
            case R.id.open_shop_iv:
                OpenShopActivity_.intent(cxt).shopStatus(shopStatus).rejectReason(rejectReason).start();
                break;
            case R.id.me_fragment_my_wallet_tv:
                WalletActivity_.intent(cxt).start();
                break;
            case R.id.me_fragment_msg_tv:
                MsgCentreActivity_.intent(cxt).start();
                break;
            case R.id.me_fragment_event_notice_tv:
                EventNoticeActivity_.intent(cxt).start();
                break;
            case R.id.me_fragment_release_dynamic_tv:
                ReleaseDynamicActivity_.intent(cxt).startForResult(Constant.ME_FRAGMENT_REQUEST_CODE);
                break;
            case R.id.me_fragment_waiting_order_tv:
                ProjectOrderManagerActivity_.intent(cxt).allProjectOrder(true).lastTab(1).start();
                break;
            case R.id.me_fragment_all_orders_tv:
                ProjectOrderManagerActivity_.intent(cxt).allProjectOrder(true).start();
                break;
            case R.id.me_fragment_cc_order_tv:
                ProjectOrderActivity_.intent(cxt).orderStatus(1).start();
                break;
            case R.id.me_fragment_product_order_tv:
                ProductOrderActivity_.intent(cxt).orderStatus(1).start();
                break;
            case R.id.me_fragment_unpay_tv:
                ProjectOrderActivity_.intent(cxt).orderStatus(2).start();
                break;
            case R.id.me_fragment_unconfirm_tv:
                ProjectOrderActivity_.intent(cxt).orderStatus(3).start();
                break;
            case R.id.me_fragment_feedback_tv:
                FeedbackActivity_.intent(cxt).start();
                break;
            default:
                break;
        }
    }
}
